var db = require("./db.js");
var socketIO = require("socket.io");

db.sync({ force: false });

module.exports = function (server) {
    var clients = [];
    var io = socketIO(server);
    var contacts = io.of("/contacts").on("connection", function (socket) {
        clients.push({
            id: socket.id,
        });
        socket.on("getAll", function () {
            db.models.user.findAll().then(function (users) {
                socket.emit("getAll", users);
            });
        });
        socket.on("getFocusList", function () {
            socket.emit("focusList", clients);
        });
        socket.on("focus", function (data) {
            clients.find(function (client) {
                return client.id === socket.id;
            }).uid = data.uid;
            contacts.emit("focusList", clients);
        });
        socket.on("blur", function (data) {
            clients.find(function (client) {
                return client.id === socket.id;
            }).uid = undefined;
            contacts.emit("focusList", clients);
            delete data.disabled;
            db.models.user.findById(data.id).then(function (user) {
                return user.update(data);
            }).then(function (user) {
                socket.broadcast.emit("blur", data);                
            });
        });
        socket.on("create", function (data) {
            db.models.user.create(data).then(function (user) {
                contacts.emit("created", user);
            }, function (err) {
                console.log(err);
            });
        });
        socket.on("disconnect", function () {
            clients.splice(clients.findIndex(function (client) {
                return client.id === socket.id;
            }), 1);
            socket.broadcast.emit("focusList", clients);
        });
    });
};